from django_system.role_recognize import check_permission
from django.http import JsonResponse
from django.views import View
from pypinyin import lazy_pinyin
import django_system.settings
from django.core.paginator import Paginator
from user.models import User, Role
from zhineng.models import Classes, College, UserInfo
import json
from django.utils.decorators import method_decorator
from functools import wraps
import jwt


class CteacherView(View):
    """查看班级信息"""

    @method_decorator(check_permission(['班主任', '老师', '院长']))
    def get(self, request):
        username = request.user
        user = User.objects.get(username=username)
        classes = user.classes_user.all().values()
        for i in classes:
            college = i['colleges_id']
            i['colleges_id'] = College.objects.filter(id=college).first().college_name
        return JsonResponse({'code': 200, 'msg': 'ok111', 'class': list(classes)})

    @method_decorator(check_permission(['班主任', '老师', '院长']))
    def post(self, request):
        data = json.loads(request.body)
        users = Classes.objects.filter(id=data['id']).first().user.all()
        stu_list = []
        for i in users:
            if Role.objects.get(name='学生') in i.roles.all():
                user_info = i.users
                stu_list.append(
                    {'username': i.username, 'phone': i.phone, 'number': user_info.number, 'age': user_info.age,
                     'address': user_info.address, 'parents': user_info.parents})
        return JsonResponse({'code': 200, 'msg': 'OK111', 'data': stu_list})


class CheckTeacherView(View):
    """查询所有老师信息"""

    @method_decorator(check_permission(['院长']))
    def get(self, request):
        dean = User.objects.filter(username=request.user).first()
        classes = College.objects.filter(college_dean=dean).first().colleges.all()
        try:
            teachers_list = []
            teachers = UserInfo.objects.filter(is_delete=False).all()
            for i in teachers:
                if Role.objects.get(name='老师') in i.user.roles.all() and i.user.classes_user.first() in classes:
                    teachers_list.append(
                        {'number': i.number, 'age': i.age, 'address': i.address, 'parents': i.parents,
                         'username': i.user.username, 'phone': i.user.phone, 'id': i.id})
            return JsonResponse({'msg': 'ok!!!!!!!!', 'data': teachers_list}, status=200)
        except Exception as e:
            return JsonResponse({'msg': '获取失败', 'code': 500}, status=500)

    @method_decorator(check_permission(['院长']))
    def post(self, request):
        data = json.loads(request.body)
        # 校验数据不能为空
        if not all(data.values()):
            return JsonResponse({'msg': "前端数据不能为空", 'code': 301})
        # 写入数据库
        try:
            new_pwd = ''.join(lazy_pinyin(data['username'])) + '123456'
            user = User.objects.create(username=data['username'], password=new_pwd, phone=data['phone'])
            UserInfo.objects.create(age=data['age'], number=data['number'], address=data['address'],
                                    parents=data['parents'], user=user)
            user.save()  # 确保 user 对象已保存到数据库
            user.roles.add(Role.objects.get(name='老师'))
            return JsonResponse({'code': 200, 'msg': '班主任信息添加成功'})
        except Exception as e:
            return JsonResponse({'msg': '班主任信息添加成功'}, status=500)

    def put(self, request):
        dean = User.objects.filter(username=request.user).first()
        classes = College.objects.filter(college_dean=dean).first().colleges.all()
        role = Role.objects.filter(name='老师').first()
        selectable = []
        for i in classes:
            hase_teacher = False
            for k in i.user.all():
                if role in k.roles.all():
                    hase_teacher = True
            if not hase_teacher:
                selectable.append({'id': i.id, 'name': i.classes_name})
        return JsonResponse({'msg': 'ok!!!!!!!!', 'data': selectable},
                            status=200)


class EditTeacher(View):
    @method_decorator(check_permission(['院长']))
    def get(self, request, id):
        try:
            teacherinfo = UserInfo.objects.filter(id=id).first()
            teacher_data = {
                'id': id,
                'username': teacherinfo.user.username,
                'phone': teacherinfo.user.phone,
                'address': teacherinfo.address,
                'parents': teacherinfo.parents,
                'age': teacherinfo.age,
                'number': teacherinfo.number
            }
            return JsonResponse({'code': 200, 'data': teacher_data}, status=200)
        except Exception as e:
            return JsonResponse({'code': 401, 'msg': '获取失败'}, status=401)

    @method_decorator(check_permission(['院长']))
    def put(self, request, id):
        data = json.loads(request.body)
        number = data['number']
        age = data['age']
        address = data['address']
        parents = data['parents']
        try:
            UserInfo.objects.filter(id=id).update(number=number, age=age, address=address, parents=parents)
            user = UserInfo.objects.filter(id=id).first().user
            user.username = data['username']
            user.phone = data['phone']
            user.save()
            return JsonResponse({'code': 200, 'msg': '修改成功'})
        except Exception as e:
            return JsonResponse({'code': 400, 'msg': f'{e}'}, status=400)


class GetClassList(View):
    @method_decorator(check_permission(['院长', '市场']))
    def get(self, request):
        colleges = College.objects.filter(is_delete=False).all()
        college_list = []
        college = list(colleges.values('id', 'college_name'))
        for i in range(len(college)):
            college_list.append(
                {'value': college[i]["id"], 'label': college[i]["college_name"]})
        for k in college_list:
            k['children'] = [{'value': i.id, 'label': i.classes_name} for i in
                             College.objects.filter(id=k['value']).first().colleges.all()]
        return JsonResponse({'code': 200, 'data': college_list}, status=200)
